package com.zjh.admin.app.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zjh.admin.app.model.VideoEntity;
import com.zjh.admin.app.service.VideoService;
import com.zjh.common.constants.Common;
import com.zjh.common.dtgrid.model.Pager;
import com.zjh.common.dtgrid.util.ExportUtils;
import com.zjh.common.result.Result;
import com.zjh.common.util.PageUtil;
import com.zjh.core.base.basecontroller.BaseController;
import com.zjh.core.exception.AjaxException;
import com.zjh.core.exception.SystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author WYX
 * @Description controller
 * @Date 2019/11/17 18:00
 */
@Controller
@RequestMapping("/video/")
public class VideoController extends BaseController {

    @Autowired
    private VideoService videoService;

    /**
     * list跳转
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("listUI.html")
    public String listUI(Model model, HttpServletRequest request) {
        try {
            PageUtil page = new PageUtil();
            if (request.getParameterMap().containsKey("page")) {
                setPage(request, page);
            }
            model.addAttribute("page", page);
            return Common.BACKGROUND_PATH + "/app/video/list";
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    /**
     * ajax分页查询视频
     *
     * @param gridPager
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping(value = "list.html")
    @ResponseBody
    public Object list(String gridPager, HttpServletResponse response) throws Exception {
        // 映射Pager对象
        Pager pager = JSON.parseObject(gridPager, Pager.class);
        // 判断是否包含自定义参数
        Map<String, Object> parameters = pager.getParameters();
        parameters.put("fastQueryMap", getFastqueryParameters(pager.getFastQueryParameters()));
        //3、判断是否是导出操作
        if (pager.getIsExport()) {
            if (pager.getExportAllData()) {
                //3.1、导出全部数据
                List<VideoEntity> list = videoService.queryListByPage(parameters);
                ExportUtils.exportAll(response, pager, list);
                return null;
            } else {
                //3.2、导出当前页数据
                ExportUtils.export(response, pager);
                return null;
            }
        } else {
            //设置分页，page里面包含了分页信息
            Page<Object> page = PageHelper.startPage(pager.getNowPage(), pager.getPageSize(), true);
            List<VideoEntity> list = videoService.queryListByPage(parameters);
            parameters.clear();
            setPageList(parameters, pager, page, list);
            return parameters;
        }
    }


    /**
     * app查询视频
     *
     * @param gridPager
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "listForApp.html")
    @ResponseBody
    public Object listForApp(String gridPager, HttpServletResponse response) throws Exception {
        // 映射Pager对象
        Pager pager = JSON.parseObject(gridPager, Pager.class);
        // 判断是否包含自定义参数
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("fastQueryMap", getFastqueryParameters(pager.getFastQueryParameters()));
        //3、判断是否是导出操作
        //设置分页，page里面包含了分页信息
        Page<Object> page = PageHelper.startPage(0, 999, true);
        List<VideoEntity> list = videoService.queryListByPage(parameters);
        parameters.clear();
        setPageList(parameters, pager, page, list);
        return parameters;
    }

    /**
     * 添加视频
     *
     * @param videoEntity
     * @return
     */
    /*@RequestMapping("add.html")
    @ResponseBody*/
    public Object add(VideoEntity videoEntity) {
        Result result = new Result();
        try {
            int status = videoService.insert(videoEntity);
            if (status > 0) {
                result.success("添加成功");
            } else {
                result.error("添加失败");
            }
        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @RequestMapping("delete.html")
    @ResponseBody
    public Object delete(String ids) {
        Result result = new Result();
        try {
            String[] videoIds = ids.split(",");
            List<Long> list = new ArrayList<>();
            for (String id : videoIds) {
                list.add(Long.valueOf(id));
            }
            int count = videoService.deleteBatchById(list);
            if (count > 0) {
                result.success("删除成功");
            } else {
                result.error("删除失败");
            }
        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

    /**
     * 文件上传
     *
     * @param files
     * @param request
     * @return 上传结果
     */
    @RequestMapping("imageUpload")
    @ResponseBody
    public Result upload(String video, MultipartFile[] files, HttpServletRequest request) {
        Result<Map> result = new Result<>();
        VideoEntity videoEntity = JSON.parseObject(video, VideoEntity.class);
        try {
            if (files != null) {
                //获取file的名
                if (files.length >= 3) {
                    String videoPath = saveFile(files[0], request, result, "video");
                    String thumbnailPath = saveFile(files[1], request, result, "thumbnail");
                    String materiaPath = saveFile(files[2], request, result, "materia");
                    for (int i = 3; i < files.length; i++) {
                        saveFile(files[i], request, result, "image");
                    }
                    videoEntity.setvPath(videoPath);
                    videoEntity.setvThumbnailPath(thumbnailPath);
                    videoEntity.setvMateriaPath(materiaPath);
                    add(videoEntity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.error("文件上传失败");
        }
        return result;
    }

    private String saveFile(MultipartFile multipartFile, HttpServletRequest request, Result<Map> result, String type) throws IOException {
        String path;
        String fileName = multipartFile.getOriginalFilename();
//        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        String fileRealPath = request.getSession().getServletContext().getRealPath("/") + Common.UPLOAD_IMAGE_PATH + "/" + type + "/";
        //自定义图片上传位置,这里是上传到项目的upload下，需要手动刷新下upload文件夹页面才能显示，如果存放在服务器的话
        //每次重启服务器图片都会消失
        String webPath = Common.UPLOAD_IMAGE_PATH + "/" + type + "/";

//        String tempName = UUID.randomUUID().toString();

        //判断文件夹是否存在
        File targerFile = new File(fileRealPath);
        if (!targerFile.exists()) {
            targerFile.mkdirs();
        }
        //保存文件
        File uploadFile = new File(fileRealPath + fileName);
        FileCopyUtils.copy(multipartFile.getBytes(), uploadFile);
        path = webPath + fileName;
        Map<String, Object> data = new HashMap<>();
        data.put("url", path);
        result.setData(data);
        result.success("上传成功");
        return path;
    }

    /**
     * 观看
     *
     * @param id
     * @return
     */
    @RequestMapping("watchVideo.html")
    @ResponseBody
    public Object watchVideo(Long id) {
        Result<Map> result = new Result<>();
        Map<String, Object> map = new HashMap<>();
        try {
            VideoEntity videoEntity = videoService.findById(id);
            if (videoEntity != null)
                videoService.updateLike(id);
            map.put("videoEntity", videoEntity);
            result.success("更新成功");
            result.setData(map);
        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

    /**
     * 收藏
     *
     * @param uId
     * @param vId
     * @return
     */
    @RequestMapping("collectVideo.html")
    @ResponseBody
    public Object collectVideo(int uId, int vId, Boolean isCollect) {
        Result result = new Result();
        Map<String, Object> map = new HashMap<>();
        map.put("uId", uId);
        map.put("vId", vId);
        System.out.println(uId + "," + vId);
        try {
            int status;
            if (isCollect)
                status = videoService.collectVideo(map);
            else
                status = videoService.deleteCollect(map);

            if (status > 0)
                result.success("成功");
            else
                result.error("失败");
        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

    /**
     *
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "listForCollect.html")
    @ResponseBody
    public Object listForCollect(int uId, HttpServletResponse response) throws Exception {
        Result result = new Result();
        List<VideoEntity> videoEntityList = videoService.findListForCollect(uId);
        if (videoEntityList != null) {
            result.success();
            result.setData(videoEntityList);
        } else
            result.error();
        return result;
    }

    /**
     * 删除
     *
     * @param uId
     * @param vIds
     * @return
     */
    @RequestMapping("deleteCollect.html")
    @ResponseBody
    public Object deleteCollect(int uId, String vIds) {
        Result result = new Result();
        try {
            vIds = vIds.replace("[","(");
            vIds = vIds.replace("]",")");
            Map<String, Object> map = new HashMap<>();
            map.put("uId",uId);
            map.put("vIds",vIds);
            int flag = videoService.deleteBatchCollectById(map);
            if (flag > 0) {
                result.success("删除成功");
            } else {
                result.error("删除失败");
            }
        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

}
